var { appHelper, timeHelper, logHelper } = require("../helper");

var apps = [
  { name: "支付宝", min: 1, max: 2, hasExec: 0 },
  { name: "袋鼠点点短视频", min: 2, max: 5, hasExec: 0 },
  { name: "百度畅听版", min: 1, max: 3, hasExec: 0 },
  { name: "西瓜视频", min: 2, max: 5, hasExec: 0, maxHasExec: 200 },
  { name: "百度极速版", min: 1, max: 3, hasExec: 0 },
];

function getHours() {
  return new Date().getHours();
}
Wang.main = function (stopHour) {
  stopHour = Number(stopHour || 0);
  if (isNaN(stopHour) || stopHour == 0) {
    stopHour = 8;
  }
  appHelper.launchApp("auto");
  sleep(2 * 1000);
  var index = 0;
  while (true) {
    run(apps);
    index++;
    if (getHours() >= stopHour) {
      break;
    } else {
      logHelper.log(`没结束: [${getHours()}] ${index}`);
    }
  }
  logHelper.log(`结束: [${getHours()}] ${index}`);
};

function run(apps) {
  var length = apps.length;
  for (var index = 0; index < length; index++) {
    var app = apps[index];
    var hasExec = app.hasExec;
    var maxHasExec = app.maxHasExec;
    if (hasExec && maxHasExec && hasExec >= maxHasExec) {
      var v = timeHelper.random(3, 5);
      logHelper.log(`${app.name}已经看满${hasExec / maxHasExec}，将打开autojs并等待${v}分钟`);
      appHelper.launchApp("auto");
      sleep(v * 1000);
    } else {
      var success = appHelper.launchApp(app.name);
      var mins = timeHelper.randomM(app.min, app.max);
      if (success) {
        logHelper.log(`${app.name}成功，将看${timeHelper.getM(mins)}分钟`);
        sleep(mins);
        app.hasExec = app.hasExec + timeHelper.getM(mins);
        logHelper.log(`${app.name}成功，已经看了${timeHelper.getM(mins)}分钟`);
      } else {
        var v = timeHelper.random(3, 5);
        logHelper.log(`${app.name}失败，将打开autojs并等待${v}分钟`);
        appHelper.launchApp("auto");
        sleep(v * 1000);
      }
    }
    appHelper.launchApp("auto");
    sleep(2 * 1000);
  }
}
